package com.example.fund.updatestategy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.json.JSONObject;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.example.fund.util.DBManager;

public class THSBKIndexStrategy extends AbstractUpdateStrategy
{

	private static String zsurl = "http://d.10jqka.com.cn/v4/line/bk_#code/01/last.js";
	private static String zsurl1 = "http://d.10jqka.com.cn/v4/line/bk_#code/01/#year.js";
	
	public THSBKIndexStrategy(String number) 
	{
		super(number);
	}

	@Override
	public void updateIndex()
	{
		SQLiteDatabase db = DBManager.getDB();

		String maxDate = getFundMaxDate();
		String curYear = Calendar.getInstance().get(Calendar.YEAR)+"";
		
		String insertSql = "insert into FundNetValue(id,fundNumber,netValue,volume,date) values (null,?,?,?,?)";
		db.beginTransaction();
		SQLiteStatement stmt = db.compileStatement(insertSql);
		
		BufferedReader reader = null;
		HttpURLConnection con = null;
		String regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
		BigDecimal tem = new BigDecimal("100000000");
		try {
			URL url = new URL(zsurl.replace("#code", number));
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
			String s = reader.readLine();
			double lastVolume = 0;
			if(s==null || s.trim().length()==0)
			{
				return;
			}
			s = s.substring(s.indexOf("{"), s.lastIndexOf("}")+1);
//			System.out.println(s);
			JSONObject jsonData = new JSONObject(s);
			JSONObject yearJSON = jsonData.getJSONObject("year");
			Iterator it = yearJSON.keys();
			Set<String> yearSet = new HashSet<String>();
			while(it.hasNext())
			{
				String year = it.next().toString();
				if(maxDate==null || maxDate.trim().length()==0
						|| year.compareTo(maxDate.substring(0, maxDate.indexOf("-")))>=0)
				{
					yearSet.add(year);
				}
			}
//			System.out.println(yearSet);
			
			for(String year:yearSet)
			{
				if(curYear.equals(year))
				{
					year = "last";
				}
				URL url1 = new URL(zsurl1.replace("#code", number).replace("#year", year));
				con = (HttpURLConnection) url1.openConnection();
				con.setRequestMethod("GET");
				reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
				String s1 = reader.readLine();
				if(s1==null || s1.trim().length()==0)
				{
					break;
				}
				s1 = s1.substring(s1.indexOf("{"), s1.lastIndexOf("}")+1);
				JSONObject jsonData1 = new JSONObject(s1);
				String data = jsonData1.getString("data");
				String[] dataArr = data.split(";");
				for(int i=0;i<dataArr.length;i++)
				{
					String dayStr = dataArr[i];
					if(dayStr.trim().length()==0)
					{
						continue;
					}
					String[] dayArr = dayStr.split(",");
					if(dayArr.length<=5)
					{
						continue;
					}
					String date = dayArr[0];
					date = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6);
					String value = dayArr[4];
					System.out.println(date+":"+value);
					
					if(date.compareTo(maxDate)>0 && Double.valueOf(value)>0)
					{
					    stmt.bindString(1, number);  
					    stmt.bindDouble(2, Double.valueOf(value));
					    double volume = lastVolume;
					    try {
					    	BigDecimal bigDecimal = new BigDecimal(dayArr[4]).divide(tem, 4, RoundingMode.HALF_UP);
					    	volume = bigDecimal.doubleValue();
						} catch (Exception e) {
						}
					    lastVolume = volume;
					    stmt.bindDouble(3, volume);
					    stmt.bindString(4, date);  
					    stmt.execute();  
					    stmt.clearBindings(); 
					}
				}
				
			}
			
			db.setTransactionSuccessful();  
		} catch(Exception e) 
		{
			e.printStackTrace();
		} finally
		{
			db.endTransaction();
			try 
			{
				if(reader!=null)
				{
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(con!=null)
			{
				con.disconnect();
			}
		}
	}

}
